package com.hdax.dmw.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdax.dmw.common.utils.Result;
import com.hdax.dmw.common.utils.ResultGenerator;
import com.hdax.dmw.entity.item.ItemType;
import com.hdax.dmw.item.dtos.IndexNavDto;
import com.hdax.dmw.item.mapstruct.NavDtoMapper;
import com.hdax.dmw.item.service.ItemTypeService;
import com.hdax.dmw.item.mappers.ItemTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author guoyisha
* @description 针对表【dm_item_type(节目类型表)】的数据库操作Service实现
* @createDate 2023-06-18 14:55:02
*/
@Service
public class ItemTypeServiceImpl extends ServiceImpl<ItemTypeMapper, ItemType>
    implements ItemTypeService{

    @Autowired
    private NavDtoMapper navDtoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //@CacheEvict(cacheNames = "navs", keyGenerator = "keyGenerator")
    @Cacheable(cacheNames = "navs", keyGenerator = "keyGenerator")
    @Override
    public Result<List<IndexNavDto>> navs() throws Exception {
        List<ItemType> types = baseMapper.types();
        List<IndexNavDto> dtos = navDtoMapper.toTargetList(types);
        return ResultGenerator.genSuccessResult(dtos);
//        ObjectMapper objectMapper = new ObjectMapper();
//        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
//        List<IndexNavDto> dtos = new ArrayList<>();
//        //判断缓存中是否存在对应的key
//        if (redisTemplate.hasKey("index:navs")) {
//            //如果存在，直接从缓存获取数据
//            //jsonString-->jackson-->object
//            String str = valueOperations.get("index:navs");
//            dtos = objectMapper.readValue(str, List.class);
//        }else{
//            //如果不存在，调用数据库，远程请求等方式获取数据，并存储在缓存
//            List<ItemType> types = baseMapper.types();
//
//            dtos = navDtoMapper.toTargetList(types);
//            //存储数据到缓存  String
//            //Object-->jackson-->string
//            String jsonString = objectMapper.writeValueAsString(dtos);
//
//            valueOperations.set("index:navs",jsonString,24L, TimeUnit.HOURS);
//        }
//        return ResultGenerator.genSuccessResult(dtos);
    }
}




